<template>
  <div class="super-agent">
    <!-- 科技感背景元素 -->
    <div class="tech-bg">
      <div class="grid-overlay"></div>
      <div class="glow-circle circle-1"></div>
      <div class="glow-circle circle-2"></div>
      <div class="data-lines">
        <div class="data-line line1"></div>
        <div class="data-line line2"></div>
        <div class="data-line line3"></div>
      </div>
      <div class="tech-particles"></div>
    </div>
    
    <div class="header">
      <div class="back-button" @click="goBack">
        <span>&larr; 返回主页</span>
      </div>
      <div class="title">
        <span class="title-text">AI 超级智能体</span>
        <div class="title-decoration"></div>
      </div>
      <div class="agent-status" :class="{ 'status-active': loading }">
        <div class="status-dot"></div>
        <span>{{ loading ? '正在处理' : '待命中' }}</span>
      </div>
    </div>
    
    <div class="chat-container">
      <div class="chat-messages" ref="messagesContainer">
        <div v-if="messages.length === 0" class="welcome-message">
          <div class="welcome-icon">
            <div class="ai-brain">
              <div class="brain-circle"></div>
              <div class="brain-pulse"></div>
            </div>
          </div>
          <h3>欢迎使用 AI 超级智能体</h3>
          <p>我可以帮助你完成复杂任务，请告诉我你的需求</p>
        </div>
        <div v-for="(message, index) in messages" :key="index" 
             :class="['message', getMessageClass(message)]">
          <div class="message-content">
            <div v-if="message.type === 'thinking'" class="message-tag">
              <span class="tag-icon">🧠</span> 思考过程
            </div>
            <div v-if="message.type === 'execution'" class="message-tag">
              <span class="tag-icon">⚙️</span> 执行结果
            </div>
            <div v-if="message.type === 'error'" class="message-tag error-tag">
              <span class="tag-icon">⚠️</span> 错误信息
            </div>
            <div class="message-text">{{ message.content }}</div>
            <div class="message-time">{{ message.time }}</div>
          </div>
        </div>
      </div>
      
      <div class="chat-input">
        <input 
          type="text" 
          v-model="userInput" 
          @keyup.enter="sendMessage" 
          placeholder="请输入指令..." 
          :disabled="loading"
        />
        <button @click="sendMessage" :disabled="loading || !userInput.trim()">
          发送
          <div class="button-glow"></div>
        </button>
      </div>
    </div>
    
    <!-- 科技装饰元素 -->
    <div class="corner-decoration top-left"></div>
    <div class="corner-decoration top-right"></div>
    <div class="corner-decoration bottom-left"></div>
    <div class="corner-decoration bottom-right"></div>
  </div>
</template>

<script>
import { chatWithManus } from '@/services/api'

export default {
  name: 'SuperAgentView',
  data() {
    return {
      eventSource: null,
      currentStepNumber: 0,
      currentStepContent: '',
      steps: [],
      userInput: '',
      messages: [],
      loading: false,
      currentStreamingMessageIndex: -1
    }
  },
  mounted() {
    // 创建粒子效果
    this.createParticles();
  },
  methods: {
    goBack() {
      this.$router.push('/')
    },
    
    // 创建背景粒子
    createParticles() {
      const particlesContainer = document.querySelector('.tech-particles');
      if (!particlesContainer) return;
      
      for (let i = 0; i < 50; i++) {
        const particle = document.createElement('div');
        particle.classList.add('particle');
        
        // 随机位置和大小
        const size = Math.random() * 3 + 1;
        particle.style.width = `${size}px`;
        particle.style.height = `${size}px`;
        particle.style.left = `${Math.random() * 100}%`;
        particle.style.top = `${Math.random() * 100}%`;
        particle.style.animationDuration = `${Math.random() * 10 + 10}s`;
        particle.style.opacity = Math.random() * 0.5 + 0.1;
        
        particlesContainer.appendChild(particle);
      }
    },
    
    getMessageClass(message) {
      if (message.type === 'user') return 'user-message';
      if (message.type === 'thinking') return 'thinking-message';
      if (message.type === 'execution') return 'execution-message';
      if (message.type === 'error') return 'error-message';
      return 'ai-message';
    },
    
    sendMessage() {
      if (!this.userInput.trim() || this.loading) return;
      
      const userMessage = {
        content: this.userInput,
        type: 'user',
        time: new Date().toLocaleTimeString()
      };
      
      this.messages.push(userMessage);
      this.loading = true;
      
      // Store the current message
      const currentMessage = this.userInput;
      this.userInput = '';
      
      this.handleSendMessage(currentMessage);
    },
    
    // Process the incoming data to identify steps
    processStreamData(data) {
      // Check if this is a new step
      if (data.includes('Step') && data.includes(':')) {
        try {
          // Extract step number
          const stepMatch = data.match(/Step(\d+):/);
          if (stepMatch && stepMatch.length > 1) {
            const stepNumber = parseInt(stepMatch[1]);
            
            // If we were already processing a step, finish it
            if (this.currentStepNumber > 0 && this.currentStepContent) {
              // Store completed step
              this.steps.push({
                number: this.currentStepNumber,
                content: this.currentStepContent
              });
              
              // Display completed step as a message
              this.receiveMessage(
                `【思考步骤 ${this.currentStepNumber}】\n${this.currentStepContent}`, 
                'thinking'
              );
            }
            
            // Start new step
            this.currentStepNumber = stepNumber;
            this.currentStepContent = data.substring(data.indexOf(':') + 1).trim();
            
            // Start a new streaming message for this step
            if (stepNumber === 1) {
              // For first step, we'll accumulate content
              return;
            } else {
              // For execution steps, we'll show streaming content
              this.startStreamingMessage('execution');
              this.updateStreamingMessage(
                `【执行步骤 ${this.currentStepNumber}】\n${this.currentStepContent}`
              );
              return;
            }
          }
        } catch (error) {
          console.error('Error parsing step number:', error);
        }
      }
      
      // If not a new step, append to current step content
      if (this.currentStepNumber > 0) {
        this.currentStepContent += data;
        
        // Update the streaming message if not the first thinking step
        if (this.currentStepNumber > 1) {
          this.updateStreamingMessage(
            `【执行步骤 ${this.currentStepNumber}】\n${this.currentStepContent}`
          );
        }
      } else {
        // If we haven't identified a step yet, treat it as a regular message
        if (data.includes('错误') || data.includes('执行错误') || data.includes('执行结束')) {
          this.receiveMessage(data, 'error');
        } else {
          this.receiveMessage(data, 'ai');
        }
      }
    },
    
    handleSendMessage(message) {
      if (this.eventSource) {
        this.eventSource.close();
      }
      
      // Reset state
      this.currentStepNumber = 0;
      this.currentStepContent = '';
      this.steps = [];
      
      this.eventSource = chatWithManus(message);
      
      this.eventSource.onmessage = (event) => {
        const data = event.data;
        if (data !== '[DONE]') {
          // Process the streaming data to handle steps
          this.processStreamData(data);
        } else {
          // If we were processing a step, finish it
          if (this.currentStepNumber > 0 && this.currentStepContent) {
            // For the last step, make sure it's displayed
            if (this.currentStepNumber === 1) {
              // If it's the first step (thinking), show as a complete message
              this.receiveMessage(
                `【思考步骤 ${this.currentStepNumber}】\n${this.currentStepContent}`, 
                'thinking'
              );
            } else {
              // If it was already streaming, just finish it
              this.finishStreamingMessage();
            }
          }
          
          // Finalize the session
          this.eventSource.close();
          this.eventSource = null;
          this.loading = false;
        }
      };
      
      this.eventSource.onerror = (error) => {
        console.error('EventSource error:', error);
        
        // If we were processing a step, finish it
        if (this.currentStepNumber > 0 && this.currentStepContent) {
          if (this.currentStepNumber > 1) {
            this.finishStreamingMessage();
          }
        }
        
        this.eventSource.close();
        this.eventSource = null;
        this.loading = false;
        
        // Show error message
        this.receiveMessage('连接错误，请稍后重试', 'error');
      };
    },
    
    // Message handling methods
    receiveMessage(content, type = 'ai') {
      const message = {
        content,
        type,
        time: new Date().toLocaleTimeString()
      };
      this.messages.push(message);
      this.scrollToBottom();
    },
    
    startStreamingMessage(type = 'ai') {
      const message = {
        content: '',
        type: type,
        time: new Date().toLocaleTimeString()
      };
      this.messages.push(message);
      this.currentStreamingMessageIndex = this.messages.length - 1;
      this.scrollToBottom();
    },
    
    updateStreamingMessage(content) {
      if (this.currentStreamingMessageIndex >= 0) {
        this.messages[this.currentStreamingMessageIndex].content = content;
        this.scrollToBottom();
      }
    },
    
    finishStreamingMessage() {
      this.loading = false;
      this.currentStreamingMessageIndex = -1;
      this.scrollToBottom();
    },
    
    scrollToBottom() {
      this.$nextTick(() => {
        if (this.$refs.messagesContainer) {
          this.$refs.messagesContainer.scrollTop = this.$refs.messagesContainer.scrollHeight;
        }
      });
    }
  },
  beforeUnmount() {
    // Close the event source when the component is unmounted
    if (this.eventSource) {
      this.eventSource.close();
      this.eventSource = null;
    }
  }
}
</script>

<style scoped>
.super-agent {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  background-color: #000c20;
  color: #e6f1ff;
}

/* 科技感背景 */
.tech-bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: hidden;
  z-index: 0;
}

.grid-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: linear-gradient(rgba(0, 157, 255, 0.05) 1px, transparent 1px),
                    linear-gradient(90deg, rgba(0, 157, 255, 0.05) 1px, transparent 1px);
  background-size: 40px 40px;
  z-index: 1;
}

.glow-circle {
  position: absolute;
  border-radius: 50%;
  filter: blur(80px);
  opacity: 0.15;
  z-index: 0;
}

.circle-1 {
  width: 300px;
  height: 300px;
  background: radial-gradient(circle, #0088ff, transparent 70%);
  top: -100px;
  right: -50px;
}

.circle-2 {
  width: 400px;
  height: 400px;
  background: radial-gradient(circle, #0055aa, transparent 70%);
  bottom: -150px;
  left: -100px;
}

.data-lines {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.data-line {
  position: absolute;
  background: linear-gradient(90deg, transparent, rgba(0, 157, 255, 0.2), transparent);
  height: 1px;
  width: 100%;
  transform-origin: left;
  animation: dataline-move 15s infinite linear;
}

.line1 {
  top: 25%;
  animation-delay: 0s;
}

.line2 {
  top: 50%;
  animation-delay: 5s;
}

.line3 {
  top: 75%;
  animation-delay: 10s;
}

@keyframes dataline-move {
  0% {
    transform: translateX(-100%);
  }
  100% {
    transform: translateX(100%);
  }
}

.tech-particles {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.particle {
  position: absolute;
  background-color: #0088ff;
  border-radius: 50%;
  opacity: 0.5;
  animation: float linear infinite;
}

@keyframes float {
  0% {
    transform: translate(0, 0);
  }
  50% {
    transform: translate(20px, -20px);
  }
  100% {
    transform: translate(0, 0);
  }
}

/* 角落装饰 */
.corner-decoration {
  position: absolute;
  width: 50px;
  height: 50px;
  border: 2px solid rgba(0, 157, 255, 0.3);
  z-index: 2;
}

.top-left {
  top: 20px;
  left: 20px;
  border-right: none;
  border-bottom: none;
}

.top-right {
  top: 20px;
  right: 20px;
  border-left: none;
  border-bottom: none;
}

.bottom-left {
  bottom: 20px;
  left: 20px;
  border-right: none;
  border-top: none;
}

.bottom-right {
  bottom: 20px;
  right: 20px;
  border-left: none;
  border-top: none;
}

/* 头部样式 */
.header {
  padding: 20px;
  background-color: rgba(5, 29, 64, 0.8);
  box-shadow: 0 1px 10px rgba(0, 157, 255, 0.2);
  display: flex;
  align-items: center;
  backdrop-filter: blur(10px);
  position: relative;
  z-index: 10;
}

.back-button {
  cursor: pointer;
  margin-right: 20px;
  padding: 8px 12px;
  border-radius: 4px;
  transition: all 0.3s ease;
  background-color: rgba(0, 71, 171, 0.3);
}

.back-button:hover {
  background-color: rgba(0, 71, 171, 0.5);
}

.back-button span {
  color: #e6f1ff;
  font-weight: 400;
  font-size: 14px;
}

.title {
  font-size: 22px;
  font-weight: 600;
  color: #e6f1ff;
  flex: 1;
  text-align: center;
  position: relative;
  text-shadow: 0 0 10px rgba(0, 157, 255, 0.5);
}

.title-text {
  background: linear-gradient(90deg, #e6f1ff, #66b6ff);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  letter-spacing: 1px;
}

.title-decoration {
  position: absolute;
  height: 3px;
  width: 60px;
  background: linear-gradient(90deg, transparent, #0088ff, transparent);
  bottom: -8px;
  left: 50%;
  transform: translateX(-50%);
}

.agent-status {
  display: flex;
  align-items: center;
  font-size: 14px;
  margin-left: 20px;
  background-color: rgba(0, 71, 171, 0.3);
  padding: 6px 12px;
  border-radius: 20px;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #66b6ff;
  margin-right: 8px;
  opacity: 0.6;
}

.status-active .status-dot {
  background-color: #00ff88;
  box-shadow: 0 0 10px #00ff88;
  animation: pulse 1s infinite;
  opacity: 1;
}

@keyframes pulse {
  0% {
    transform: scale(0.8);
    opacity: 0.8;
  }
  50% {
    transform: scale(1.2);
    opacity: 1;
  }
  100% {
    transform: scale(0.8);
    opacity: 0.8;
  }
}

/* 内容区域 */
.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  width: 100%;
  padding: 0 20px;
  overflow: hidden;
  position: relative;
  z-index: 5;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 15px 0;
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 10px;
  scrollbar-width: thin;
  scrollbar-color: rgba(0, 157, 255, 0.5) rgba(5, 29, 64, 0.5);
}

.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background-color: rgba(0, 157, 255, 0.5);
  border-radius: 10px;
}

.chat-messages::-webkit-scrollbar-track {
  background-color: rgba(5, 29, 64, 0.5);
}

.welcome-message {
  text-align: center;
  margin: auto;
  padding: 30px;
  background-color: rgba(5, 29, 64, 0.4);
  border-radius: 12px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(0, 157, 255, 0.2);
  max-width: 500px;
}

.welcome-icon {
  margin-bottom: 20px;
}

.ai-brain {
  width: 80px;
  height: 80px;
  position: relative;
  margin: 0 auto;
}

.brain-circle {
  position: absolute;
  width: 60px;
  height: 60px;
  background: radial-gradient(circle, #0088ff, #004080);
  border-radius: 50%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  box-shadow: 0 0 30px rgba(0, 136, 255, 0.8);
}

.brain-pulse {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 60px;
  height: 60px;
  border: 2px solid rgba(0, 157, 255, 0.5);
  border-radius: 50%;
  animation: brain-pulse 2s infinite;
}

@keyframes brain-pulse {
  0% {
    width: 60px;
    height: 60px;
    opacity: 1;
  }
  100% {
    width: 100px;
    height: 100px;
    opacity: 0;
  }
}

.welcome-message h3 {
  color: #e6f1ff;
  font-size: 22px;
  margin-bottom: 10px;
  text-shadow: 0 0 10px rgba(0, 157, 255, 0.5);
}

.welcome-message p {
  color: #a9c6ff;
  font-size: 16px;
}

.message {
  display: flex;
  margin-bottom: 10px;
  max-width: 85%;
}

.user-message {
  justify-content: flex-end;
  align-self: flex-end;
}

.ai-message, .thinking-message, .execution-message, .error-message {
  justify-content: flex-start;
  align-self: flex-start;
}

.message-content {
  max-width: 100%;
  padding: 12px 18px;
  border-radius: 12px;
  position: relative;
  word-break: break-word;
  overflow-wrap: break-word;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.2);
}

.message-tag {
  font-size: 12px;
  margin-bottom: 5px;
  font-weight: bold;
}

.error-tag {
  color: #ff4040;
}

.user-message .message-content {
  background-color: rgba(0, 71, 171, 0.8);
  border-bottom-right-radius: 3px;
  color: #e6f1ff;
  border: 1px solid rgba(0, 157, 255, 0.3);
}

.ai-message .message-content {
  background-color: rgba(5, 29, 64, 0.8);
  border-bottom-left-radius: 3px;
  color: #e6f1ff;
  border: 1px solid rgba(0, 157, 255, 0.2);
  box-shadow: 0 0 10px rgba(0, 157, 255, 0.1);
}

.ai-message .message-tag {
  color: #66b6ff;
  background-color: rgba(102, 182, 255, 0.15);
  padding: 3px 8px;
  border-radius: 4px;
  display: inline-block;
}

.thinking-message .message-content {
  background-color: rgba(0, 35, 80, 0.7);
  border-left: 3px solid #0088ff;
  border-bottom-left-radius: 3px;
  color: #e6f1ff;
  position: relative;
  padding-left: 20px;
}

.thinking-message .message-tag {
  color: #00ccff;
  background-color: rgba(0, 136, 255, 0.15);
  padding: 3px 8px;
  border-radius: 4px;
  display: inline-block;
}

.execution-message .message-content {
  background-color: rgba(5, 40, 20, 0.7);
  border-left: 3px solid #00ff88;
  border-bottom-left-radius: 3px;
  color: #e6f1ff;
  position: relative;
  padding-left: 20px;
}

.execution-message .message-tag {
  color: #00ff88;
  background-color: rgba(0, 255, 136, 0.15);
  padding: 3px 8px;
  border-radius: 4px;
  display: inline-block;
}

.error-message .message-content {
  background-color: rgba(64, 5, 5, 0.7);
  border-left: 3px solid #ff4040;
  border-bottom-left-radius: 3px;
  color: #ffe6e6;
  position: relative;
  padding-left: 20px;
}

.error-message .message-tag {
  color: #ff4040;
  background-color: rgba(255, 64, 64, 0.15);
  padding: 3px 8px;
  border-radius: 4px;
  display: inline-block;
}

.message-text {
  word-break: break-word;
  white-space: pre-wrap;
  overflow-wrap: break-word;
  max-width: 100%;
  overflow-x: auto;
  line-height: 1.5;
}

.message-time {
  font-size: 11px;
  color: rgba(230, 241, 255, 0.6);
  text-align: right;
  margin-top: 5px;
}

.chat-input {
  display: flex;
  padding: 15px 0;
  margin-bottom: 10px;
  flex-shrink: 0;
  position: sticky;
  bottom: 0;
  background-color: rgba(0, 12, 32, 0.7);
  width: 100%;
  z-index: 10;
  backdrop-filter: blur(10px);
  border-top: 1px solid rgba(0, 157, 255, 0.2);
}

.chat-input input {
  flex: 1;
  padding: 12px 18px;
  border: 1px solid rgba(0, 157, 255, 0.3);
  border-radius: 24px;
  outline: none;
  margin-right: 12px;
  background: rgba(5, 29, 64, 0.6);
  color: #e6f1ff;
  font-size: 16px;
  transition: all 0.3s ease;
}

.chat-input input:focus {
  border-color: rgba(0, 157, 255, 0.8);
  box-shadow: 0 0 0 2px rgba(0, 157, 255, 0.2);
}

.chat-input input::placeholder {
  color: rgba(230, 241, 255, 0.5);
}

.chat-input button {
  padding: 12px 24px;
  background: linear-gradient(135deg, #0088ff, #0044aa);
  color: white;
  border: none;
  border-radius: 24px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  font-size: 16px;
}

.button-glow {
  position: absolute;
  top: -30%;
  left: -10%;
  width: 120%;
  height: 160%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transform: skewX(-20deg);
  animation: button-glow 3s infinite;
  opacity: 0;
  transition: opacity 0.3s;
}

.chat-input button:hover .button-glow {
  opacity: 1;
}

@keyframes button-glow {
  0% {
    left: -30%;
  }
  100% {
    left: 130%;
  }
}

.chat-input button:hover:not(:disabled) {
  background: linear-gradient(135deg, #00a0ff, #0055cc);
  box-shadow: 0 0 15px rgba(0, 136, 255, 0.5);
  transform: translateY(-2px);
}

.chat-input button:disabled {
  background: linear-gradient(135deg, #335577, #223344);
  color: rgba(230, 241, 255, 0.5);
  cursor: not-allowed;
}

@media (max-width: 768px) {
  .agent-status {
    display: none;
  }
  
  .header {
    padding: 15px 10px;
  }
  
  .title {
    font-size: 18px;
  }
  
  .chat-container {
    padding: 0 10px;
  }
  
  .message {
    max-width: 95%;
  }
}

.thinking-message .message-text {
  color: #b3d9ff;
  font-family: monospace;
  font-size: 0.95em;
}

.execution-message .message-text {
  color: #c6ffe6;
  font-family: monospace;
  font-size: 0.95em;
}

.error-message .message-text {
  color: #ffcccc;
  font-family: monospace;
  font-size: 0.95em;
}

.tag-icon {
  margin-right: 4px;
  font-size: 14px;
}
</style> 